# == Coding: UTF-8 ==
# @Project :        BooksManagementSystem
# @fileName         admin_function.py  
# @version          v0.5
# @author           LIULONG
# @GiteeWarehouse   https://gitee.com/liu-long068/
# @WritingTime      2023/6/3 0:00
# @Software:        PyCharm
# ====/******/=====
import json
import random
import sys


class AdministratorOperationFunction:
    def __init__(self):
        self.path = r'D:\BooksManagementSystem\public\users\student.json'
        self.users = []
        self.load_users()

    def load_users(self):
        # 先读取已有的 JSON 文件
        try:
            with open(self.path, 'r', encoding='utf-8') as file:
                self.users = json.load(file)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f'Error loading user data: {e}')

    def save_users(self, data, msg="学生信息录入成功！"):
        try:
            with open(self.path, 'w', encoding='utf-8') as file:
                json.dump(data, file, ensure_ascii=False, indent=4)
                print(msg)
        except FileNotFoundError as e:
            print(f'Error saving user data: {e}')

    def inputs_student_information(self):
        """ 录入学生信息 """
        self.load_users()
        student_info = {}
        stu_id = str(input("学号："))
        student_info['学号'] = stu_id
        self.detect_duplicate_stuId(stu_id)
        student_info['姓名'] = str(input("学生姓名："))
        student_info['性别'] = str(input("性别："))
        student_info['身份证号'] = str(input("身份证号："))
        student_info['联系电话'] = str(input("学生联系电话："))
        student_info['二级学院'] = str(input("二级学院："))
        student_info['专业'] = str(input("专业："))
        student_info['班级'] = self.generate_class(student_info['二级学院'], student_info['专业'], student_info['学号'])
        student_info['状态'] = 1  # 状态默认为 1
        self.users.append(student_info)
        sorted_data = sorted(self.users, key=lambda x: x['学号'])
        self.save_users(sorted_data)

    def query_student_borrow_information(self):
        """ 查询学生借阅信息 """
        pass

    def query_Alldisable_student_information(self):
        """ 查询所有禁用学生信息 """
        all_disable = [user for user in self.users if user['状态'] == 0]
        for disable in all_disable:
            print(disable)

    def query_Allblacklist_student_information(self):
        """ 查询所有黑名单学生信息 """
        all_blacklists = [user for user in self.users if user['状态'] == 2]
        for blacklist in all_blacklists:
            print(blacklist)

    def add_blacklist(self):
        """ 新增黑名单 """
        stu_id = str(input("需要加入黑名单的学生学号："))
        student = self.query_student_by_id_information(stu_id)
        if student:
            student['状态'] = 2
            self.save_users(self.users, msg=f"学号为【{stu_id}】的学生已被加入黑名单！")

    def disable_student_borrow_permission(self):
        """ 禁用学生借阅权限 """
        stu_id = str(input("需要禁用学生借阅权限的学生学号："))
        student = self.query_student_by_id_information(stu_id)
        if student:
            student['状态'] = 0
            self.save_users(self.users, msg=f"学号为【{stu_id}】的学生已被禁用借阅权限！")

    def remove_student_disable_permission(self):
        """ 解除学生禁用权限 """
        stu_id = str(input("需要解除禁用学生借阅权限的学生学号："))
        student = self.query_student_by_id_information(stu_id)
        if student:
            student['状态'] = 1
            self.save_users(self.users, msg=f"学号为【{stu_id}】的学生禁用借阅权限已成功解除！")

    def normal_exit(self):
        """ 退出 """
        print("退出成功！欢迎再次使用！")
        sys.exit()

    def generate_class(self, college, major, student_id):
        year = int(student_id[:2])
        grade = year + 2000
        x = random.choice([1, 2, 3, 4, 5])
        return f"{major}{grade}级{x}班"

    def detect_duplicate_stuId(self, stu_id):
        """ 检测学号是否重复 """
        if stu_id in [user['学号'] for user in self.users]:
            print(f"学号【{stu_id}】已存在！")
            return False

    def query_student_by_id_information(self, stu_id):
        """ 查询指定学号的学生信息 """
        for user in self.users:
            if user['学号'] == stu_id:
                return user
        print(f"未找到学号为【{stu_id}】的学生信息！")
